package com.pengxun.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.entity.ContentType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.pengxun.manager.model.system.Userinfo;
import com.pengxun.manager.service.system.LoginService;
import com.pengxun.manager.service.system.RoleMenuService;
import com.szeastroc.common.constant.ErrorCode;
import com.szeastroc.common.exception.EastrocException;
import com.szeastroc.common.result.Result;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

	@Resource
	private LoginService loginService;

	@Resource
	private RoleMenuService roleMenuService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (request.getRequestURI().contains("/cityCode")||request.getRequestURI().contains("/code/getBarCode")) {
			return true;
		}
		if (request.getMethod().equalsIgnoreCase("GET")
				&& (request.getRequestURI().contains("/downloadError")
						|| request.getRequestURI().contains("/errMsgDownload")
				|| request.getRequestURI().contains("/downloadTmp")
				|| request.getRequestURI().contains("/downloadZIP")
		)) {
			return true;
		}

		//重置密码
		if (request.getRequestURI().contains("/sendResetPasswordEmail")
				|| request.getRequestURI().contains("/doResetPasswordEmail")
				|| request.getRequestURI().contains("/sendResetPasswordValidateCode")
				|| request.getRequestURI().contains("/validateResetPasswordValidateCode")
				|| request.getRequestURI().contains("/doResetPasswordmobile")){
			return true;
		}
		String token = request.getHeader("authorization");

		if (StringUtils.isEmpty(token)) {
			Result result = buildFailedResult("authorization not empty");
			renderJson(response, JSON.toJSONString(result));
			return false;
		}
		Userinfo userinfo = null;
		try {
			userinfo = loginService.getCurrentUser();
		} catch (EastrocException e) {
			Result result = buildFailedResult(e.getMessage());
			response.setStatus(Integer.parseInt(ErrorCode.NO_LOGIN.getCode()));
			renderJson(response, JSON.toJSONString(result));
			return false;
		} catch (Exception e) {
			Result result = new Result();
			result.setCode(ErrorCode.ERROR.getCode());
			result.setMsg(ErrorCode.ERROR.getMsg());
			response.setStatus(Integer.parseInt(ErrorCode.ERROR.getCode()));
			renderJson(response, JSON.toJSONString(result));
			return false;
		}


		return true;
	}

	private Result buildFailedResult(String message) {
		Result result = new Result();
		result.setCode(ErrorCode.NO_LOGIN.getCode());
		result.setMsg(message);
		return result;
	}

	private void renderJson(HttpServletResponse response, String jsonText) {
		PrintWriter writer = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
			writer = response.getWriter();
			writer.write(jsonText);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
